package com.zilue.payment.gateway.manage;

import com.alibaba.fastjson.JSON;
import com.zilue.balance.domain.UserAccount;
import com.zilue.balance.returnresult.Result;
import com.zilue.payment.gateway.common.FeeChannelEnums;
import com.zilue.payment.gateway.common.RefundStatusEnums;
import com.zilue.payment.gateway.domain.CorpDO;
import com.zilue.payment.gateway.domain.PayOrderDO;
import com.zilue.payment.gateway.domain.RefundLogDO;
import com.zilue.payment.gateway.mapper.CorpMapper;
import com.zilue.payment.gateway.mapper.PayOrderMapper;
import com.zilue.payment.gateway.mapper.RefundLogMapper;
import com.zilue.payment.gateway.method.remote.UserAccountRemote;
import com.zilue.payment.gateway.paramter.order.RefundParameter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * Created by zilue on 2017/3/9.
 */
public class BaseManager {
    private static final Logger logger = Logger.getLogger(BaseManager.class);

    @Autowired
    private UserAccountRemote userAccountRemote;
    @Autowired
    private CorpMapper corpMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;
    @Autowired
    public PayOrderMapper payOrderMapper;


    public UserAccount queryByCard(String cardNo, Integer cardType) {
        Result<UserAccount> userAccountResult = userAccountRemote.getUser(cardNo, cardType);
        if (userAccountResult != null && userAccountResult.getData() != null) {
            return userAccountResult.getData();
        } else {
            return null;
        }
    }

    public CorpDO queryCorpByAppid(String appid) {
        try {
            CorpDO corpDO = corpMapper.queryByAppId(appid);
            return corpDO;
        } catch (Exception e) {
            logger.error("APPID获取医院信息出现异常，请检查数据信息。" + "\t\nappid：" + appid + "\t\nthirdApp：" + appid, e);
            return null;
        }
    }

    public CorpDO queryCorpBySubCorpId(Long subCorpId) {
        try {
            CorpDO corpDO = corpMapper.queryByCorpId(subCorpId);
            return corpDO;
        } catch (Exception e) {
            logger.error("subCorpId获取医院信息出现异常，请检查数据信息。" + "\t\nsubCorpId：" + subCorpId, e);
            return null;
        }
    }

    public PayOrderDO queryByOrderNoOutTradeNo(String orderNo, String outTradeNo, String outPayNo, Long corpId, Long subCorpId) {
        List<PayOrderDO> payOrderDOList = payOrderMapper.queryByOrderNoOutTradeNo(orderNo, outTradeNo, outPayNo, corpId, subCorpId);
        if (payOrderDOList.isEmpty()) {
            return null;
        } else if (payOrderDOList.size() > 1) {
            logger.error("发现多笔支付订单！！！ 严重！！" + JSON.toJSONString(payOrderDOList));
            return payOrderDOList.get(0);
        }
        return payOrderDOList.get(0);
    }

    public PayOrderDO queryByOrderNo(String orderNo, Long corpId, Long subCorpId) {
        List<PayOrderDO> payOrderDOList = payOrderMapper.queryByOrderNo(orderNo, corpId, subCorpId);
        if (payOrderDOList.isEmpty()) {
            return null;
        } else if (payOrderDOList.size() > 1) {
            logger.error("发现多笔支付订单！！！ 严重！！" + JSON.toJSONString(payOrderDOList));
            return payOrderDOList.get(0);
        }
        return payOrderDOList.get(0);
    }

    public RefundLogDO insertRefundLog(PayOrderDO payOrder, RefundParameter refundParameter) {

        RefundLogDO refundLogDO = RefundLogDO.builder().outTradeNo(payOrder.getOutTradeNo()).corpId(payOrder.getSubCorpId())
                .outRefundNo(refundParameter.getOut_refund_no()).fee(refundParameter.getFee()).reason(refundParameter.getReason())
                .terminalId(refundParameter.getTerminal_id()).operatorId(refundParameter.getOperator_id())
                .feeChannel(FeeChannelEnums.BALANCE.getCode()).status(RefundStatusEnums.PROCESSING.getCode()).build();
        long row = refundLogMapper.insert(refundLogDO);
        if (row > 0)
            return refundLogDO;
        else
            return null;
    }

    public RefundLogDO queryRefundLog(String outTradeNo, String outRefundNo) {
        RefundLogDO refundLogDO = refundLogMapper.queryByOutTradeNoAndOutRefundNo(outTradeNo, outRefundNo);
        return refundLogDO;
    }

    public boolean updateRefundLogStatus(Long id, Integer oldStatus, Integer newStatus) {
        int row = refundLogMapper.updateStatusByPK(id, oldStatus, newStatus);
        if (row > 0)
            return true;
        else
            return false;
    }
    public boolean updateRefundLogStatus(String outTradeNo,String outRefundNo, Integer oldStatus, Integer newStatus) {
        int row = refundLogMapper.updateStatus(outTradeNo,outRefundNo, oldStatus, newStatus);
        if (row > 0)
            return true;
        else
            return false;
    }

    public boolean updatePayOrderRefundFee(Long id, Long oldFee, Long fee) {//更新时将旧值带上，是采用了乐观锁的原理。
        Long newRefundFee = oldFee + fee;
        int row = payOrderMapper.updateRefundFee(id, oldFee, newRefundFee);
        if (row > 0)
            return true;
        else
            return false;
    }

    public boolean updatePayOrderStatus(Long id, Integer oldStatus, Integer newStatus) {//更新时将旧值带上，是采用了乐观锁的原理。
        int row = payOrderMapper.updateStatus(id, oldStatus, newStatus);
        if (row > 0)
            return true;
        else
            return false;
    }

    public boolean addPayOrderOutPayNo(Long id, String  outPayNo) {//更新第三方订单号
        int row = payOrderMapper.updateOutPayNo(id, outPayNo);
        if (row > 0)
            return true;
        else
            return false;
    }

    public boolean updatePayOrderPayDate(Long id, Date date) {
        int row = payOrderMapper.updatePayDate(id, date);
        if (row > 0)
            return true;
        else
            return false;
    }
}
